#coding:utf-8
import json
from django.http import HttpResponse
from django.contrib.auth.decorators import login_required
from lovewith.utils.mtcache import MtCache
from lovewith.website.views.modules.category import CategoryApi
from lovewith.subscribe.views.modules.recommand import get_recommand_keywords
from lovewith.subscribe.views.modules.subscribe import SubscribeApi



#添加或删除订阅关键词
@login_required
def edit_keyword(request):
    action = request.GET.get('a')
    keyword = request.GET.get('k')
    key_list = request.GET.get('ks')
    cate_id = request.GET.get('c')
    result = {'error': True}
    key_words = []
    if keyword:
        key_words.append(keyword)
    if key_list:
        key_words.extend(key_list.split('@_!'))

    if len(key_words) > 0:
        state = False
        if action == 'del':
            for key in key_words:
                state = SubscribeApi().delete(key, request.user)
            #删除缓存
            for i in range(4):
                MtCache('subscribe_share').delete(user_id=request.user.id, page=(i+1))
        if action == 'add' and keyword:
            cate_data = None
            if cate_id:
                cate_data = CategoryApi.check_data(cate_id=int(cate_id))
            state = SubscribeApi().add(keyword, cate_data, request.user)

            #删除缓存
            for i in range(4):
                MtCache('subscribe_share').delete(user_id=request.user.id, page=(i+1))

        if state:
            result = {'error': False}

    return HttpResponse(json.dumps(result))


#批量添加订阅类目
@login_required
def add_keyword(request):
    result = {'error': True}
    cate_ids = request.POST.getlist('cid')

    for cate_id in cate_ids:
        cate_data = CategoryApi.check_data(cate_id=int(cate_id))
        if cate_data:
            SubscribeApi().add(cate_data.name, cate_data, request.user)

        result = {'error': False}

    return HttpResponse(json.dumps(result))


#分页数据
@login_required
def get_subscribe(request):
    page_no = int(request.GET.get('page', 1))
    command_keyword = get_recommand_keywords(page_no)

    result = {
        'total_page': command_keyword.get('total_page'),
        'page': page_no,
        'data': command_keyword.get('keywords')
    }

    return HttpResponse(json.dumps(result))